var layerLoad;
var layerNum;
var layNum=null;
/**
 * 页面初始化加载
 */
(function(){
	initCouponList(1);
    initCoupon();
	/*日期插件*/
    var startDate = new Date().toLocaleDateString();
    var endDate = new Date().toLocaleDateString();
    var $alert = $('#my-alert');//提示框
    $('#my-start').datepicker().on('changeDate.datepicker.amui', function(event) {
        if (event.date.valueOf() > endDate.valueOf()) {
            $alert.find('p').text('开始日期应小于结束日期！').end().show();
        } else {
            $alert.hide();
            startDate = new Date(event.date);
            $('#beginDate').text($('#my-start').data('date'));
        }
        $(this).datepicker('close');
    });
    $('#my-end').datepicker().on('changeDate.datepicker.amui', function(event) {
        if (event.date.valueOf() < startDate.valueOf()) {
            $alert.find('p').text('结束日期应大于开始日期！').end().show();
        } else {
            $alert.hide();
            endDate = new Date(event.date);
            $('#endDate').text($('#my-end').data('date'));
        }
        $(this).datepicker('close');
    });
})();

/*初始化*/
function initCouponList(currentPage){
	var sysProduct = {
		currentPage : currentPage
	};
	$.ajax({
		url : $api.coupon.selectCoupons,
		type : "POST",
		dataType : "JSON",
		contentType : 'application/json',
		data :JSON.stringify(sysProduct),
		beforeSend : function () {
			layerLoad = layer.load();
		},
		success : function(data) {
			if(!$checkRemouteStatus(data)){
				layer.close(layerLoad);
				return;
			}
			var newData=data;
            $.each(newData.msg,function(index,data){
                data.beginDate=new Date(data.beginDate).toLocaleDateString().replace(/\//g,"-");
                data.endDate=new Date(data.endDate).toLocaleDateString().replace(/\//g,"-");
			});
			layui.use('laytpl', function() {
				var laytpl = layui.laytpl;
				laytpl(sysProductListTpl.innerHTML).render(newData, function(html) {
					$('#system-coupon-list-body').html(html)
				});
			});
			layui.use('laypage', function() {
				layui.laypage({
					cont: $('#system-coupon-page'),
					pages: data.totalPage,
					groups: 2,
					curr: data.currentPage,
					skip: true,
                    skin:'#0e90d2;',
					jump: function (obj,first) {
						if(!first){
							initCouponList(obj.curr);
						}
					}
				});
			});
			layer.close(layerLoad);
		},
		error : function() {
			layer.close(layerLoad);
			layer.msg('网络异常，请稍后再试', {icon: 2});
		}
	});
};
/*初始化会员等级和商品分类*/
function initCoupon(){
    $.ajax({
        url : $api.productCategory.selectProductCategorysForInsertCoupon,
        type : "GET",
        dataType : "JSON",
        contentType : 'application/json',
        beforeSend : function () {
        },
        success : function(data) {
            if(!$checkRemouteStatus(data)){
                layer.close(layerLoad);
                return;
            }
            var productTxt="";
            $.each(data.msg,function(index,dataObj){
                productTxt+="<label class='am-checkbox-inline'><input class='product'  type='checkbox' value="+dataObj.id+">"+dataObj.name+"</label>";
			});
            $("#selectProductCategorys").html(productTxt);
        },
        error : function() {
            layer.close(layerLoad);
            layer.msg('网络异常，请稍后再试', {icon: 2});
        }
    });
    $.ajax({
        url : $api.memberBank.selectMemberRanks,
        type : "GET",
        dataType : "JSON",
        contentType : 'application/json',
        beforeSend : function () {
        },
        success : function(data) {
            if(!$checkRemouteStatus(data)){
                layer.close(layerLoad);
                return;
            }
            var memberTxt="";
            $.each(data.msg,function(index,dataObj){
                memberTxt+="<label class='am-checkbox-inline'><input class='member'  type='checkbox' value="+dataObj.id+">"+dataObj.name+"</label>";
            });
            $("#selectMemberRanks").html(memberTxt);
        },
        error : function() {
            layer.close(layerLoad);
            layer.msg('网络异常，请稍后再试', {icon: 2});
        }
    });
};
/**
 * 搜索
 */
$('#sys-product-form-list-search').submit(function(e){
	e.preventDefault();
	initCouponList(1);
});

/**
 * 详情查询
 */
var id="";
$('#system-coupon-list-body').on('click','.btn-system-coupon-update',function(){
	var couponId=$(this).attr("couponId");
	$.ajax({
		url : $api.coupon.selectCouponById+"?couponId="+couponId,
		type : "GET",
		dataType : "JSON",
        contentType : 'application/json',
		beforeSend : function () {
			layerLoad = layer.load();
		},
		success : function(data,e) {
			if(!$checkRemouteStatus(data)){
				layer.close(layerLoad);
				return;
			}
			var dataObj=data.msg;
            id=dataObj.id;
			$('#name').val(dataObj.name);
            $('#prefix').val(dataObj.prefix);
            $('#beginDate').text(new Date(dataObj.beginDate).toLocaleDateString().replace(/\//g,"-"));
            $('#endDate').text(new Date(dataObj.endDate).toLocaleDateString().replace(/\//g,"-"));
            $('#minimumPrice').val(dataObj.minimumPrice);
            $('#priceExpression').val(dataObj.priceExpression);
            var isEnabled="";
            dataObj.isEnabled ? isEnabled = 1 : isEnabled = 0;
            $('#isEnabled').val(isEnabled);
            $('#orders').val(dataObj.orders);
            Selected("#selectMemberRanks input:checkbox",dataObj.memberRankIds);
            Selected("#selectProductCategorys input:checkbox",dataObj.productCategoryIds);
			layer.close(layerLoad);
		},
		error : function() {
			layer.close(layerLoad);
			layer.msg('网络异常，请稍后再试', {icon: 2});
		}
	});
	layNum=layer.open({
		type : 1,
		title : '优惠劵',
		area : 'auto',
		maxWidth : '1000px',
		content : $('#sys-product-update-model'),
		cancel : function(){
			$('#sys-product-form-update')[0].reset();
			$('#sysProductImgUrlUpdate').attr('src',$assets.headChooseIcon);
		}
	});
});

/*新增*/
$("#couponAdd").click(function(){
    id=false;
    /*清除数据*/
    $("#selectProductCategorys input").removeAttr("checked");
    $("#selectMemberRanks input").removeAttr("checked");
	$("#endDate").text("");
    $("#beginDate").text("");
    $("#priceExpression").val("");
    $("#minimumPrice").val("");
    $('#name').val("");
    layNum=layer.open({
        type : 1,
        title : '优惠劵',
        area : 'auto',
        maxWidth : '1000px',
        content : $('#sys-product-update-model'),
        cancel : function(){
            $('#sys-product-form-update')[0].reset();
            $('#sysProductImgUrlUpdate').attr('src',$assets.headChooseIcon);
        }
    });
});

function dateAuto(text){
    var textArr=text.split("-");
    var moth="";
    var day="";
    textArr[1]<10?moth="0"+parseInt(textArr[1]):moth=textArr[1];
    textArr[2]<10?day="0"+parseInt(textArr[2]):day=textArr[2];
    return textArr[0]+"-"+moth+"-"+day;
};
/*checked拼接*/
function checkedTxt(domTxt){
    var ranksTxt="";
    $(domTxt).each(function(index,dom){
        if($(dom).is(':checked')){
            ranksTxt+=","+$(dom).val();
        };
    });
    var ranksResult = ranksTxt.substring(1);
    return ranksResult;
};
/*checked复显*/
function Selected(domTxt,dataTxt){
    console.log(dataTxt);
    var productCategoryIds=dataTxt.split(",");
    console.log(productCategoryIds);
    $(domTxt).each(function(index,dom){
        if(productCategoryIds.indexOf($(dom).val())!== -1){
            $(dom)[0].checked=true;
        }else{
            $(dom)[0].checked=false;
        }
    });
};
$("#save").on("click",function(){
	/*必填验证*/
	var ajaxFlag=1;
	$('#sys-product-update-model input[required="required"]').each(function(index,dom){
		if($(dom).val()===""){
		   $(dom).addClass("am-field-error");
			layer.msg("填写不完整，请检查", {icon: 2});
			ajaxFlag=0;
			return
		}
	});
	if(ajaxFlag==0){
		return
	}	
	if($('#beginDate').text()==""||$('#endDate').text()==""){
		layer.msg("日期不能为空", {icon: 2});
		return
		}
	var dataObj={};
	if(id!==false){
        dataObj.id=id;
	};
    dataObj.name=$('#name').val();
    dataObj.prefix=$('#prefix').val();
    dataObj.beginDateStr=dateAuto($('#beginDate').text());
    dataObj.endDateStr=dateAuto($('#endDate').text());
    dataObj.minimumPrice=$('#minimumPrice').val();
    dataObj.priceExpression=$('#priceExpression').val();
    dataObj.isEnabledFlag=$('#isEnabled').val();
    dataObj.orders=$('#orders').val();
    dataObj.memberRankIds=checkedTxt("#selectMemberRanks input:checkbox");
    dataObj.productCategoryIds=checkedTxt("#selectProductCategorys input:checkbox");
    $.ajax({
        url : $api.coupon.insertCoupon,
        type : "POST",
        dataType : "JSON",
        contentType : 'application/json',
        data :JSON.stringify(dataObj),
        beforeSend : function () {
            layerLoad = layer.load();
        },
        success : function(data) {
            if(!$checkRemouteStatus(data)){
                layer.close(layerLoad);
                return;
            }
            if(data.code=="000000"){
                layer.close(layerLoad);
                layer.close(layNum);
                initCouponList(1);
                layer.msg(data.msg, {icon: 1});
            }
        },
        error : function() {
            layer.close(layerLoad);
            layer.msg('网络异常，请稍后再试', {icon: 2});
        }
    });
});

/*非负数限定*/
$("#sys-product-update-model").on("change",".isPositive",function(){
    isPositive(this.value,this);
});
$("#sys-product-update-model").on("keyup",".isPositive",function(){
    isPositive(this.value,this);
});
function isPositive(tet,othis){
	if(tet.substr(0, 1)==="0"){
        $(othis).val("");
        return
    }
    tet=tet.replace(/[^0-9]/g,'');
    $(othis).val(tet);
};